package com.example.wx_basketball.controller.mall;

import com.example.wx_basketball.entity.mall.ShoppingCart;
import com.example.wx_basketball.service.mall.ShoppingCartService;
import com.example.wx_basketball.utils.RedisUtil;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;


@RequestMapping("/shopping-cart")
@RestController
public class ShoppingCartController {

    @Resource
    ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public void addProduct(int productId, int userId) {
        // 先查询数据库中该用户是否有该产品，如果有，直接数量++。否则新增一条数据
        ShoppingCart shoppingCart = shoppingCartService.getByProductId(productId, userId);
        if (shoppingCart == null)
            shoppingCartService.add(productId, userId);
        else shoppingCartService.updateCount(productId, userId);

        // 对于加购的商品，将 productId 等记录在 redis 中
        Jedis jedis = RedisUtil.getConnecttion();

        // 通过有序集合 zset 实现点击量的统计
        Double score = jedis.zscore("products", "productId-" + productId);
        if (score == null) {
            jedis.zadd("products", 1, "productId-" + productId);
        } else {
            jedis.zincrby("products", 1, "productId-" + productId);
        }

        jedis.close();
    }

    @PostMapping("/cut")
    public void cutProduct(int productId, int userId) {
        shoppingCartService.cutCount(productId, userId);
    }

    @DeleteMapping("/delete")
    public void deleteByProductId(Integer productId, int userId) {
        shoppingCartService.deleteByProductId(productId, userId);
    }

    @GetMapping("/all")
    public List getShoppingCartByUid(int userId) {
        return shoppingCartService.getShoppingCartByUid(userId);
    }

}
